package xwj.example.demo.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import xwj.example.demo.domain.Product;
import xwj.example.demo.exception.ProductAdminException;
import xwj.example.demo.service.IProductService;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xwj
 * @since 2022-10-30
 */
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    IProductService productService;

    @GetMapping("/{id}")
    public ResponseEntity<Product> getProduct(@PathVariable long id){
        Product result = productService.getProduct(id);
        if(result==null) {
            return ResponseEntity.noContent().build();
        }else{
            return ResponseEntity.ok(result);
        }
    }


    @GetMapping("")
    public IPage<Product> findProduct(String name, Float price, Float stockQuantity, String category,
                                      String productType, String supplierName,
                                      @RequestParam(defaultValue = "0")Integer pageNum,
                                      @RequestParam(defaultValue = "10")Integer pageSize){
        Map<String,Object> condition=new HashMap<>();
        if(name!=null) {
            condition.put("name",name);
        }
        if(price!=null) {
            condition.put("price",price);
        }
        if(category!=null) {
            condition.put("category",category);
        }
        if(stockQuantity!=null) {
            condition.put("stockQuantity",stockQuantity);
        }
        if(productType!=null) {
            condition.put("productType",productType);
        }
        if(supplierName!=null) {
            condition.put("supplierName",supplierName);
        }
        return productService.findProduct(condition, pageNum,pageSize);
    }



    @PostMapping("")
    public Product addProduct(@RequestBody Product product) throws ProductAdminException {
        return productService.addProduct(product);
    }


    @PutMapping("/{id}")
    public void updateProduct(@PathVariable long id,@RequestBody Product product) throws ProductAdminException {
        productService.updateProduct(id,product);
    }


    @DeleteMapping("/{id}")
    public void deleteProduct(@PathVariable long id){
        productService.deleteProduct(id);
    }

}

